<?php

namespace app\api\biz;

use app\common\biz\Biz;
use app\common\enum\Code;
use app\common\model\biz\SysRole;
use app\common\model\biz\SysUserRole;
use app\common\Result;
use Exception;
use think\db\exception\DbException;

class UserRoleBiz extends Biz
{

    public static function list(int $userId): UserRoleBiz
    {
        if (empty($userId)) {
            return self::errorByCode(Code::ParamsInvalid);
        }
        $lists = SysUserRole::where('user_id', $userId)->select();
        $lists = $lists->toArray();

        self::setName($lists, SysRole::column('name', 'id'), 'role_id');

        return self::success($lists);
    }

    public static function add(int $userId, array $roleIds): UserRoleBiz
    {
        if (empty($userId)) {
            return self::errorByCode(Code::ParamsInvalid);
        }

        try {
            SysUserRole::where('user_id', $userId)->delete();
            foreach ($roleIds as $roleId) {
                SysUserRole::create(['user_id' => $userId, 'role_id' => $roleId]);
            }
            return self::success();
        } catch (DbException $e) {
            Result::dbException($e->getData());
        } catch (Exception $e) {
            Result::httpException($e->getMessage());
        }
    }
}